<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useForm } from '@/hooks/arco/useForm';
  import { useUploader } from '@/hooks/useUploader';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import {
    createPerArchive,
    updatePerArchive,
    queryTotalArchives,
    queryPerArchiveInfo,
    genResourceUploadToken,
  } from '@/api/reemployment-management/document';
  import { queryTraineeList } from '@/api/reemployment-management/trainee';
  import * as Lodash from 'lodash';
  import { fillData, getInfoFromImageResource } from '@/views/lhj-v1/util';
  import PhotoItem from './photo-item.vue';

  const emits = defineEmits(['cancel', 'update']);
  const props = defineProps({
    id: {
      type: String,
      default: '',
    },
  });

  const baseNameMap = {
    id: { key: 'id', label: '个人档案id' },
    title: {
      key: 'topArchiveId',
      label: '参培题目',
      placeholder: '请选择参培题目',
    },
    trainee: {
      key: 'studentId',
      label: '培训学员',
      placeholder: '请选择培训学员',
    },
    satisfactionResources: { key: 'satisfactionResources' },
    trainingStyleResources: { key: 'trainingStyleResources' },
    //
  };

  const trainTitleOptions = useSelectOption<any, any[]>({
    apiFun: queryTotalArchives,
    initQueryParams: [{ pageNum: 1, pageSize: 10000 }],
    fieldNames: {
      label: 'title',
      value: 'id',
    },
  });
  const traineeOptions = useSelectOption<any, any[]>({
    apiFun: queryTraineeList,
    initQueryParams: [{ page: 1, pageSize: 10000 }],
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const loading = ref(false);
  const infoBase = useForm({
    state: {
      [baseNameMap.id.key]: '',
      [baseNameMap.title.key]: '',
      [baseNameMap.trainee.key]: '',
    },
    rules: {
      [baseNameMap.title.key]: {
        required: true,
        message: baseNameMap.title.placeholder,
      },
      [baseNameMap.trainee.key]: {
        required: true,
        message: baseNameMap.trainee.placeholder,
      },
    },
  });

  
  const uploader1 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card',
      defaultFileList: [],
    },
  });
  
  const uploader2 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card',
      defaultFileList: [],
    },
  });

  const handleSave = async () => {
    await infoBase.validate();
    loading.value = true;
    const data: any = Lodash.cloneDeep(infoBase.state);
    data[baseNameMap.satisfactionResources.key] = uploader1.getResourceIds();
    data[baseNameMap.trainingStyleResources.key] = uploader2.getResourceIds();
    let apiFunc = createPerArchive;
    let msg = '创建成功！';
    if (props.id) {
      apiFunc = updatePerArchive;
      msg = '保存成功！';
    }
    apiFunc(data)
      .then((res) => {
        Message.success(msg);
        emits('update');
      })
      .catch((err) => {})
      .finally(() => {
        loading.value = false;
      });
  };

  watch(
    () => props.id,
    (newVal) => {
      if (newVal) {
        loading.value = true;
        queryPerArchiveInfo(newVal)
          .then((res) => {
            infoBase.state = fillData(infoBase.state, res);
            const imgItems1 = Lodash.cloneDeep(res[baseNameMap.satisfactionResources.key])
            console.log('imgItems1:', imgItems1);
            if (imgItems1) {
              uploader1.props.defaultFileList = [];
              for (let i=0 ; i<imgItems1.length; i+=1) {
                uploader1.props.defaultFileList?.push(getInfoFromImageResource(imgItems1[i]))
              }
              console.log(uploader1.props.defaultFileList)
            }
            const imgItems2 = Lodash.cloneDeep(res[baseNameMap.trainingStyleResources.key])
            if (imgItems2) {
              uploader2.props.defaultFileList = [];
              for (let i=0 ; i<imgItems2.length; i+=1) {
                uploader2.props.defaultFileList?.push(getInfoFromImageResource(imgItems2[i]))
              }
            }
          })
          .catch((err) => {})
          .finally(() => {
            loading.value = false;
          });
      }
    },
    { immediate: true }
  );
</script>

<template>
  <div class="md-per-add">
    <div class="md-ta-item md-ta-form">
      <div><span style="font-weight: 600; font-size: 15px">基本信息</span></div>
      <a-form
        style="margin-top: 10px"
        v-bind="infoBase.bindProps"
        layout="vertical"
        :wrapper-col-props="{ span: 3 }"
      >
        <!-- 1 -->
        <a-row justify="space-between">
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.title.key"
              :label="baseNameMap.title.label"
              required
            >
              <a-select
                v-bind="trainTitleOptions.bindProps"
                v-model="infoBase.state[baseNameMap.title.key]"
                allow-clear
                :placeholder="baseNameMap.title.placeholder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.trainee.key"
              :label="baseNameMap.trainee.label"
              required
            >
              <a-select
                v-bind="traineeOptions.bindProps"
                v-model="infoBase.state[baseNameMap.trainee.key]"
                allow-clear
                :placeholder="baseNameMap.trainee.placeholder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="7"></a-col>
        </a-row>
      </a-form>
    </div>
    <div class="md-ta-imgs" v-if="!loading">
      <PhotoItem title="满意度调查表" :uploader="uploader1" />
      <PhotoItem title="培训风采" :uploader="uploader2" />
    </div>
    <div class="m-bottom-btns" style="padding-right: 30px">
      <a-space>
        <ae-button purpose="cancel" @click="emits('cancel')">取消</ae-button>
        <ae-button purpose="save" @click="handleSave">保存</ae-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .md-per-add {
    color: var(--color-text-1);
    padding: 10px;
    padding-bottom: 40px;
    height: calc(100% - 30px);
    overflow-x: hidden;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .md-ta-item {
    padding: 10px 20px 2px;
    border-radius: 4px;
    background-color: var(--color-fill-1);
    margin-bottom: 20px;
  }

  .md-ta-imgs {
    display: flex;
    flex-direction: column;
    row-gap: 10px;
  }
</style>
